package com.tuantuan.common.base.result;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.tuantuan.common.base.common.IServerErrorCode;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.Date;

/**
 * <p>
 * REST API 返回结果
 * </p>
 *
 * @author wangqinmin
 * @date 2018-11-08
 * @description: 仰天大笑出门去，我辈岂是蓬蒿人
 */
@Data
@Accessors(chain = true)
@ApiModel(value= "统一返回参数包装", description= "返回参数包装类")
public class Responses<T> implements Serializable {

    private static final long serialVersionUID = 9176125179872407986L;

    @ApiModelProperty("响应码(0:失败 1:成功)")
    private long code;

    @ApiModelProperty("响应数据")
    private T data;

    @ApiModelProperty("响应消息")
    private String msg;

    @ApiModelProperty("响应时间")
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    private Date time = new Date();

    /**
     * 执行成功
     *
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Responses<T> ok(T data) {
        ApiCode aec = ApiCode.SUCCESS;
        if (data instanceof Boolean && Boolean.FALSE.equals(data)) {
            aec = ApiCode.FAILED;
        }
        return restResult(aec, null, data, null, null);
    }

    /**
     * 操作失败
     *
     * @param msg
     * @param <T>
     * @return
     */
    public static <T> Responses<T> failed(String msg) {
        return restResult(ApiCode.FAILED, msg, null, null, "操作失败");
    }


    /**
     * 操作失败（返回服务端失败原因及状态码）
     *
     * @param errorCode
     * @param <T>
     * @return
     */
    public static <T> Responses<T> failed(IServerErrorCode errorCode, String errorMsg) {
        return restResult(ApiCode.FAILED, null, null, errorCode, errorMsg);

    }

    public static <T> Responses<T> restResult(ApiCode aec, String msg, T data, IServerErrorCode errorCode, String errorMsg) {
        Responses<T> apiResult = new Responses<>();
        apiResult.setCode(aec.getCode());
        apiResult.setData(data);
        apiResult.setMsg(aec.getMsg());
        if (aec.getCode() != ApiCode.SUCCESS.getCode() && msg == null) {
            apiResult.setData((T) new ResponsesServer(errorCode.getCode(), errorCode.getMsg(), errorMsg));
        }
        return apiResult;
    }

}
